import { useState, useCallback, useEffect } from "react";
import { View, ScrollView } from "@tarojs/components";
import { Empty } from "@nutui/nutui-react-taro";
import {
  IHeaderBox,
  IBarCharts,
  IUserItem,
  IloadMore,
} from "@/components/index";
import { colChartStat, statListClass } from "@/axios/subject";
import { getTypeList } from "@/axios/common";
import "./index.scss";

interface MIProps {}

interface FormDataProps {
  pageNum: number;
  pageSize: number;
  mapId: number | null;
}

const MIIndex: React.FC<MIProps> = () => {
  const [listData, setListData] = useState<API.ExamDetailClassItem[]>([]);
  const [chartData, setChartData] = useState<API.ChartStatItem[]>([]);
  const [options, setOptions] = useState<API.OptionItem[]>([]);
  const [currentType, setCurrentType] = useState<API.OptionItem>({});
  const [formData, setFormData] = useState<FormDataProps>({
    pageNum: 1,
    pageSize: 1,
    mapId: null,
  });
  const [loadStatus, setLoadStatus] = useState<
    "more" | "loading" | "noMore" | undefined
  >("more");
  const [otherInfo, setOtherInfo] = useState<
    Pick<API.TableResProps<null>, "pages">
  >({
    pages: 2,
  });

  const [triggered, setTriggered] = useState<boolean>(false);

  const getTypeData = async () => {
    try {
      const results = await getTypeList({ subjectId: 2 });
      const optionsData = results?.map((item) => ({
        value: item.mapId,
        text: item.name,
      }));
      if (optionsData.length > 0) {
        setCurrentType(optionsData[0]);
        setFormData({
          pageNum: 1,
          pageSize: 10,
          mapId: optionsData[0].value as number,
        });
      }
      setOptions(optionsData);
      // getListData();
    } catch {}
  };

  const getChartData = async () => {
    try {
      const results = await colChartStat();
      setChartData(results);
    } catch {}
  };

  const getListData = useCallback(async () => {
    try {
      if (!formData.mapId) return;
      if (formData.pageNum > 1) setLoadStatus("loading");
      const { list = [], ...other } = await statListClass({ ...formData });
      if (formData.pageNum == 1) {
        setListData(list);
      } else {
        setListData((preState) => [...preState, ...list]);
      }
      setLoadStatus(other.pages > formData.pageNum ? "more" : "noMore");
      setOtherInfo(other);
      setTriggered(false);
    } catch {}
  }, [formData]);

  const onRefresh = () => {
    getChartData();
    setTriggered(true);
    getTypeData();
  };

  const handleChangeCurrentType = (data: API.OptionItem) => {
    setCurrentType(data);
    setFormData({
      pageNum: 1,
      pageSize: 10,
      mapId: data.value as number,
    });
  };

  useEffect(() => {
    getListData();
  }, [getListData]);

  useEffect(() => {
    getTypeData();
    getChartData();
  }, []);

  const handlerBottom = () => {
    if (otherInfo.pages == formData.pageNum) {
      setLoadStatus("noMore");
    } else {
      setFormData({
        ...formData,
        pageNum: formData.pageNum + 1,
      });
      setLoadStatus("loading");
    }
  };

  return (
    <ScrollView
      scrollY
      className="scrollview"
      onRefresherRefresh={onRefresh}
      enableBackToTop
      refresherEnabled
      refresherTriggered={triggered}
      scrollWithAnimation
      onScrollToLower={handlerBottom}
    >
      <View className="common_page">
        <View className="card_box chart_box">
          <IHeaderBox title="学科兴趣" />
          <IBarCharts id="si_chart" data={chartData} />
        </View>
        <View className="card_box data_box">
          <IHeaderBox
            title="学科人数"
            type={1}
            options={options}
            selectData={currentType}
            handleChange={handleChangeCurrentType}
          />
          <View className="data_info">
            {listData.length > 0 ? (
              <>
                {listData.map((item: API.ExamDetailClassItem) => (
                  <IUserItem key={item.userName} sourceData={item} />
                ))}
                <IloadMore loadStatus={loadStatus} />
              </>
            ) : (
              <Empty imageSize={120} />
            )}
          </View>
        </View>
      </View>
    </ScrollView>
  );
};

export default MIIndex;
